/**
 * COPYRIGHT HangZhou Trustway Technology Company Limited
 * All right reserved.
 */
package com.robam.cloud.database.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author 薛铁琪
 * @CreateTime 2020/7/5 12:37
 * @Version 1.0
 */
@Configuration
@Slf4j
public class MyDruidBuilder {


    @ConfigurationProperties(
            prefix = "robam.component.database.druid"
    )
    @Bean
    public DruidConfiguration druidConfiguration() {
        log.debug("component-databaselog-----------加载druid配置信息");
        return new DruidConfiguration();
    }


    @Bean
    public ServletRegistrationBean druidServletRegistrationBean(@Qualifier("druidConfiguration") DruidConfiguration druidConfiguration) {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings(new String[]{"/druid/*"});
        servletRegistrationBean.addInitParameter("allow", druidConfiguration.getAllow() == null ? "127.0.0.1" : druidConfiguration.getAllow());
        servletRegistrationBean.addInitParameter("deny", druidConfiguration.getDeny() == null ? "192.168.10.250" : druidConfiguration.getDeny());
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        servletRegistrationBean.addInitParameter("loginUsername", druidConfiguration.getLoginUsername() == null ? "test" : druidConfiguration.getLoginUsername());
        servletRegistrationBean.addInitParameter("loginPassword", druidConfiguration.getLoginPassword() == null ? "test" : druidConfiguration.getLoginPassword());
        log.debug("component-databaselog-----------加载druid servletRegistrationBean配置信息");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean duridFilterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        Map<String, String> initParams = new HashMap();
        initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
        filterRegistrationBean.setInitParameters(initParams);
        filterRegistrationBean.addUrlPatterns(new String[]{"/*"});
        log.debug("component-databaselog-----------加载druid filterRegistrationBean配置信息");
        return filterRegistrationBean;
    }
}
